<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    dataBar1: { type: Object as () => any, default: [] },
    dataBar2: { type: Object as () => any, default: [] },
    dataBar3: { type: Object as () => any, default: [] },
    dataLine1: { type: Object as () => any, default: [] },
    dataLine2: { type: Object as () => any, default: [] },
    dataLine3: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    yAxisName: { type: Object as () => any, default: [] },
    barName: { type: Object as () => any, default: [] },
    lineName: { type: Object as () => any, default: [] },
    title: { type: String, default: '' },
    other: { type: Object as () => any, default: [] },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const allSeries = [
    {
      barWidth: '20px',
      name: props.barName[0],
      type: 'bar',
      data: props.dataBar1,
      yAxisIndex: 0,
      itemStyle: {
        color: '#409eff',
      },
    },
    {
      name: props.barName[1],
      barWidth: '20px',
      type: 'bar',
      data: props.dataBar2,
      yAxisIndex: 0,
      itemStyle: {
        color: '#00eaff',
      },
    },
    {
      name: props.barName[2],
      barWidth: '20px',
      type: 'bar',
      data: props.dataBar3 ?? [],
      yAxisIndex: 0,
      itemStyle: {
        color: 'rgb(121, 187, 255)',
      },
      // tooltip: {
      //   show: false,
      // },
    },
    {
      name: props.lineName[0],
      type: 'line',
      data: props.dataLine1,
      yAxisIndex: 1,
      symbol: 'circle',
      symbolSize: 4,
      itemStyle: { color: '#409eff' },
    },
    {
      name: props.lineName[1],
      type: 'line',
      data: props.dataLine2,
      yAxisIndex: 1,
      symbol: 'circle',
      symbolSize: 4,
      itemStyle: { color: '#00eaff' },
    },
    {
      name: props.lineName[2],
      type: 'line',
      data: props.dataLine3,
      yAxisIndex: 1,
      symbol: 'circle',
      symbolSize: 4,
      itemStyle: { color: '#6A5ACD' },
    },
  ];

  const option = ref<any>({
    title: {
      text: props.title, // 图表标题
      left: 'center', // 标题居中
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#fff',
      },
    },
    tooltip: {
      trigger: 'axis', // 坐标轴触发 tooltip
      appendToBody: true, // 关键设置
      // confine: true,
      position: function (point: any) {
        return [point[0], point[1] + 20]; // 将提示框向下偏移20像素
      },

      formatter: function (params: any[]) {
        let html = `<div>${params[0].name}</div>`;
        params.forEach((item) => {
          let value = item.value;
          if (item.value == 0 && props.other && props.other.length > 0) {
            value = props.other[params[0].dataIndex];
          }
          html += `
            <div style="display: flex; align-items: center; margin-top: 4px;">
              <span
                style="display: inline-block; width: 10px; height: 10px; border-radius: 50%;
                       background-color: ${item.color}; margin-right: 8px;"
              ></span>
              <span>${item.seriesName}: ${value}</span>
            </div>
          `;
        });
        return html;
      },
    },
    legend: {
      data: [...props.barName, ...props.lineName].length > 1 ? [...props.barName, ...props.lineName] : [], // 对应 series 的 name，按需修改
      top: props.title == '' ? '5%' : '15%', // 图例位置
      textStyle: {
        color: '#fff',
        fontSize: 12,
      },
    },
    grid: {
      left: '2%',
      right: '4%',
      bottom: '10%',
      containLabel: true, // 让 grid 包含坐标轴文本
    },
    xAxis: {
      type: 'category',
      data: props.datax ?? [], // X 轴类目
      axisLine: { lineStyle: { color: '#fff' } },
      axisLabel: { color: '#fff' },
    },
    yAxis: [
      {
        type: 'value',
        name: props.yAxisName[0],
        axisLabel: {
          formatter: '{value}',
        },
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { show: false },
        nameTextStyle: { color: '#fff' },
        min: 0,
      },
      {
        type: 'value',
        name: props.yAxisName[1],
        scale: true,
        // axisLabel: {
        //   formatter: '{value}' + '%',
        // },
        position: 'right', // 右侧 Y 轴
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { show: false },
        nameTextStyle: { color: '#fff' },
      },
    ],
    series: [],
  });

  const initCharts = () => {
    try {
      formatterOption();
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    formatterOption();
    option.value.title.text = props.title;
    // option.value.series[0].data = props.dataBar1 ?? [];
    option.value.xAxis.data = props.datax ?? [];
    chartInstance?.setOption(option.value, true);
    handleResize();
  };

  const formatterOption = () => {
    const series = [];
    if (props.dataBar1.length > 0) {
      allSeries[0].data = props.dataBar1 ?? [];
      series.push(allSeries[0]);
    }
    if (props.dataBar2.length > 0) {
      allSeries[1].data = props.dataBar2 ?? [];
      series.push(allSeries[1]);
    }
    if (props.dataBar3.length > 0) {
      allSeries[2].data = props.dataBar3 ?? [];
      series.push(allSeries[2]);
    }
    if (props.dataLine1.length > 0) {
      allSeries[3].data = props.dataLine1 ?? [];
      series.push(allSeries[3]);
    }
    if (props.dataLine2.length > 0) {
      allSeries[4].data = props.dataLine2 ?? [];
      series.push(allSeries[4]);
    }
    if (props.dataLine3.length > 0) {
      allSeries[5].data = props.dataLine3 ?? [];
      series.push(allSeries[5]);
    }
    option.value.series = [];
    option.value.series = series;
    option.value.yAxis[0].name = props.yAxisName[0];
    option.value.yAxis[1].name = props.yAxisName[1];
    let isLegend = [...props.barName, ...props.lineName].length > 1;
    option.value.legend.data = isLegend ? [...props.barName, ...props.lineName] : [];
    option.value.title.text = props.title;
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      initCharts();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.dataBar1, props.dataBar2, props.dataBar3, props.dataLine1, props.dataLine2, props.dataLine3],
    () => updateChart(),
    { deep: true }
  );

  watch(
    () => props.title,
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
  });

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
